package com.bluesky.jwf.util.state;

import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;

import com.bluesky.jwf.component.Form;
import com.bluesky.jwf.component.Page;
import com.bluesky.jwf.component.window.MainWindow;
import com.bluesky.jwf.util.JWFServlet;
import com.bluesky.jwf.util.ResourceUtil;
import com.bluesky.jwf.util.ServletContext;
import com.bluesky.jwf.util.StatePersistenceType;

public class ClientStateHandler extends AbstractStateHandler implements StateHandler {
	public static String STATE_HASH = "state.hash";

	@Override
	public Object get(HttpServletRequest req, ServletContext context) {

		String viewStateStr = (String) context
				.getParameter(Form.FIELD_VIEW_STATE);
		if (viewStateStr == null)
			return null;

		byte[] viewStateBuf = ResourceUtil.base64Decode(viewStateStr);
		byte[] hash = ResourceUtil.md5(viewStateBuf);
		byte[] hashInSession = (byte[]) req.getSession().getAttribute(
				STATE_HASH);
		// if the hash value mismatch, state is lost
		if (hashInSession == null || !Arrays.equals(hashInSession, hash))
			return null;

		Object obj = (MainWindow) ResourceUtil
				.readObjectFromByteArray(viewStateBuf);
		return obj;
	}

	@Override
	public void store(HttpServletRequest req, MainWindow window, Page page) {
		// put state data to hidden field
		// add the view-state field temporarily

		byte[] viewStateBuf = ResourceUtil.writeObjectToByteArray(window);
		byte[] hash = ResourceUtil.md5(viewStateBuf);

		// save the hash, will be used to check when postback
		req.getSession().setAttribute(STATE_HASH, hash);

		String viewStateStr = ResourceUtil.base64Encode(viewStateBuf);

		page.getForm().getViewStateField().setAttribute("value", viewStateStr);

	}

}
